package com.scc.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.scc.pojo.*;
import com.scc.service.AdminOperationLogService;
import com.scc.service.AdminService;
import com.scc.service.EmpOperationLogService;
import com.scc.utils.AliOSSUtil;
import com.scc.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {
    //注入service层admin类
    @Autowired
    private AdminService adminService;

    //注入管理员日志接口
    @Autowired
    private AdminOperationLogService adminOperationLogService;

    //注入文件上传的工具类
    @Autowired
    private AliOSSUtil aliOSSUtil;

    //注入员工日志接口
    @Autowired
    private EmpOperationLogService empOperationLogService;


    ///登录功能开发
    //post请求 路径为login 存在json对象
    @PostMapping("/login")
    public Result login(@RequestBody Admin admin) {
        //记录日志
        log.info("管理员登陆:{}", admin);
        //根据传入的json对象来在数据库查询 得到请求体的内容
        Admin admin1 = adminService.select(admin);
        //如果admin1不是null 说明登录成功（生成jwt令牌） 反之数据库中不存在该用户 登录失败
        if (admin1 != null) {
            //下面执行生成jwt令牌的操作
            Map <String, Object> claims = new HashMap<>();
            claims.put("id",admin1.getId());///id
            claims.put("username",admin1.getUsername());///管理员的账号
            claims.put("password",admin1.getPassword());///管理员的密码
            claims.put("rights",admin1.getRights());///管理员的权限
            //调用工具类JwtUtil生成jwt令牌
            String jwt = JwtUtil.generateJwt(claims);
            //将jwt令牌的信息返回前端 和权限的数据返回前端
            Integer rights = admin1.getRights();
            List<Object> adminLoginMsg = new ArrayList<>();
            adminLoginMsg.add(jwt);
            adminLoginMsg.add(rights);
            return Result.success(adminLoginMsg);
        }
        //没有该用户的信息则返回失败信息
        return Result.error("登录失败");
    }

    ///获取管理员信息更具账号
    @GetMapping()
    public Result getAdminMsg(String account) {
        adminService.getAdminMsg(account);
        return Result.success();
    }

    ///管理员修改密码的操作,put方法
    @PutMapping()
    public Result updatePassword(@RequestBody Admin admin) {
        //记录日志
        log.info("管理员:{}", admin.getUsername());
        log.info("将密码修改为:{}", admin.getPassword());
        adminService.updatePassword(admin);
        //无需返回data
        return Result.success();
    }
    ///管理员新增员工开发
    @PostMapping("/emps")
    public Result addEmp(@RequestBody Emp emp) {
        log.info("新增员工信息:{}", emp);
        //创建新增员工方法，根据传入的对象，在数据库中添加员工信息,无需返回值
        adminService.addEmp(emp);
        //返回正确的结果
        return Result.success();
    }

    ///员工头像上传
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        //记录日志
        log.info("文件上传的名称:{}", file.getOriginalFilename());
        //上传阿里云，得到图片的url
        String url = aliOSSUtil.upload(file);
        log.info("文件对应的url:{}", url);
        //返回url并在前端展示
        return Result.success(url);
    }
    ///员工表所有信息的查询 get请求，查询说有信息并做好分页
    @GetMapping("/emps")
    //页数，每一页的大小，名字，性别，账号，开始时间，结束时间（查询创造时间）
    public Result allEmp(@RequestParam(value = "page",defaultValue = "1") Integer page,
                         @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                          String name, Integer gender, String account,
                         @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate beginTime,
                         @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime) {
        //记录日志
        log.info("员工表信息查询");
        //转化为pageBean对象,查询对于的信息，并在前端做好分页展示
        PageBean pageBean = adminService.pageSearch(page,pageSize,name,gender,account,beginTime,endTime);
        return Result.success(pageBean);
    }
    ///管理员删除员工操作
    @DeleteMapping("/emp/{id}")
    public Result deleteEmpById(@PathVariable Integer id) {
        log.info("根据id删除员工:{}",id);
        //删除操作无需返回值
        adminService.delete(id);
        //返回成功的结果，无需data
        return Result.success();
    }
    ///管理员批量删除员工信息操作
    @DeleteMapping("/emps/{ids}")
    public Result deleteEmpByIds(@PathVariable List<Integer> ids) {
        log.info("根据id的集合删除员工:{}",ids);
        //连接server层 无需返回值
        adminService.deleteByIds(ids);
        return Result.success();
    }
    ///根据id获取用户对象
    @GetMapping("/emps/{id}")
    public Result getEmpById(@PathVariable Integer id) {
        log.info("获取对象的数据根据id:{}",id);
        //需要返回一个员工对象
        Emp emp = adminService.getEmpMessage(id);
        //传入list集合前端需要展示的数据
        //返回一个对象
        return Result.success(emp);
    }
    ///根据id修改员工数据
    @PutMapping("/emps")
    public Result modify(@RequestBody Emp emp) {
        //记录日志
        log.info("修改的员工信息为:{}",emp);
        //无需返回对象
        adminService.modifyEmp(emp);
        //无需返回data
        return Result.success();
    }
    ///新增考勤日期（post请求）
    //前端传过来的是，考勤名称，考勤时间，考勤截止时间
    @GetMapping("/attendance")
    public Result addAttendance(@RequestParam("attendanceName") String attendanceName,
                                @RequestParam("attendanceDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate attendanceDate,
                                @RequestParam("endAttendanceTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endAttendanceTime) {
        log.info("管理员添加考勤名称:{}",attendanceName);
        //获取所有用户的姓名，性别，账名，工资信息（list集合）//无需返回值
        adminService.getAllEmpMessage(attendanceName,attendanceDate,endAttendanceTime);
        //添加无需返回数据
        return Result.success();
    }

    ///获取考勤数据的操作
    //传入页数，页数大小，名称，性别，账号，用户考勤状态
    @GetMapping("/attendances")
    public Result getAllAttendance(@RequestParam(defaultValue = "1") Integer page,
                                   @RequestParam(defaultValue = "10") Integer pageSize,
                                   String name, Integer gender, String account,
                                   Integer empAttendanceStatus,
                                   @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate attendanceDate){
        log.info("查询考勤表操作");
        //需要返回一个分页数据对象
        PageBean pageBean = adminService.getAllAttendance(page,pageSize,name,gender,account,empAttendanceStatus,attendanceDate);
        //返回分页数据
        return Result.success(pageBean);
    }
    ///根据id删除考勤信息
    @DeleteMapping("/attendance/{ids}")
    public Result deleteAttendance(@PathVariable List<Integer> ids) {
        log.info("删除考勤表数据的id:{}",ids);
        //无需返回值
        adminService.deleteAttendanceByIds(ids);
        //无需返回数据
        return Result.success();
    }
    ///根据id进行扣除工资操作(PUT请求) JSON包含(id集合)(工资大小)
    @PutMapping("/attendance")
    public Result deductSalary(@RequestBody String deductMessage) throws JsonProcessingException {
        log.info("扣除工资的信息:{}",deductMessage);
        //无需返回值’
        adminService.deductSalary(deductMessage);
        //无需返回数据
        return Result.success();
    }

    ///查询或者获取全部员工请假信息表
    @GetMapping("/leaves")
    public Result getEmpLeaveMeg(@RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                 String name,Integer gender,String account,
                                 @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
                                 @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate){
        log.info("员工请假信息表获取");
        //返回一个pageBean对象(包含中的记录数，和包含员工请假对象的集合)
        PageBean empLeaveMsg = adminService.getEmpLeaveMsg(page,pageSize,name,gender,account,startDate,endDate);
        //返回集合给前端
        return Result.success(empLeaveMsg);
    }

    ///修改员工审批状态(put请求)
    @PutMapping("/leaves")
    public Result modifyEmpLeaveApproveStatus(@RequestBody String approveStatusMsg) throws JsonProcessingException {
        //记录日志
        log.info("请假审批的操作信息L{}",approveStatusMsg);///1，通过 2，不通过
        //无需返回值
        adminService.modifyEmpLeaveApproveStatus(approveStatusMsg);
        //无需返回数据给前端
        return Result.success();
    }

    ///查询员工离职或这获取全部信息
    @GetMapping("/resigns")
    public Result getEmpResignMsg(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  String name,Integer gender,String account,
                                  @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
                                  @DateTimeFormat (pattern = "yyyy-MM-dd") LocalDate endDate) {
    log.info("获取员工离职信息");
    //返回一个分页对象数据
    PageBean pageBean = adminService.getEmpResignMsg(page,pageSize,name,gender,account,startDate,endDate);
    //返回前端一个分页数据对象
    return Result.success(pageBean);
    }
    ///管理员审批员工离职申请（put请求）
    @PutMapping("/resigns")
    public Result modifyEmpResignApproveStatus(@RequestBody String resignApproveStatus) throws JsonProcessingException {
        //记录日志
        log.info("离职审批的操作信息:{}",resignApproveStatus);
        //无需返回值
        adminService.modifyEmpResignApproveStatus(resignApproveStatus);
        //无需返回数据给前端
        return Result.success();
    }

    ///管理员对团建活动的查询或者获取团建信息的获取
    @GetMapping("/teamBuildingActivities")
    public Result getTeamBuildingActivitiesMsg(@RequestParam(defaultValue = "1") Integer page,
                                               @RequestParam(defaultValue = "10") Integer pageSize,
                                               String teamBuildingName,Integer activityStatus,
                                               @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime begin,
                                               @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end) {
        log.info("获取团建活动表的信息");
        //返回分页对象
        PageBean pageBean = adminService.getTeamBuildingActivitiesMsg(page,pageSize,teamBuildingName,activityStatus,begin,end);
        //返回分页对象
        return Result.success(pageBean);
    }

    ///管理员添加团建活动
    @PostMapping("/teamBuildingActivities")
    public Result addTeamBuildingActivities(@RequestBody TeamBuildingActivities teamBuildingActivities){
        log.info("新增团建活动信息:{}",teamBuildingActivities);
        //无需返回对象
        adminService.addTeamBuildingActivities(teamBuildingActivities);
        //无需返回数据给前端
        return Result.success();
    }

    ///管理员删除团建活动的操作
    @DeleteMapping("/teamBuildingActivities/{ids}")
    public Result deleteTeamBuildingActivities(@PathVariable List<Integer> ids) {
        log.info("要删除团建活动的ids:{}",ids);
        //无需返回值
        adminService.deleteTeamBuildingActivities(ids);
        //无需返回数据
        return Result.success();
    }

    ///根据id获取团建活动的信息
    @GetMapping("/teamBuildingActivities/{id}")
    public Result getTeamBuildingActivitiesMsg(@PathVariable Integer id) {
        log.info("获取团建活动的id:{}",id);
        //返回一个团建活动的对象
        TeamBuildingActivities teamBuildingActivities = adminService.getTeamBuildingActivitiesMsgById(id);
        //返回一个团建活动对象数据给前端
        return Result.success(teamBuildingActivities);
    }

    ///修改团建活动的信息
    @PutMapping("/teamBuildingActivities")
    public Result modifyTeamBuildingActivities(@RequestBody String teamBuildingActivities){
        log.info("修改后的团建活动信息:{}",teamBuildingActivities);
        adminService.modifyTeamBuildingActivities(teamBuildingActivities);
        //无需返回数据给前端
        return Result.success();
    }

    ///获取单个团建活动的员工报名情况或者查询
    @GetMapping("/empTeamBuildingActivities")
    public Result geEmpTeamBuildingActivitiesMsg(@RequestParam(defaultValue = "1") Integer page,
                                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                                 String name,Integer gender,String account,String activityDuration,
                                                 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime begin,
                                                 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end,
                                                 Integer id,Integer empActivityStatus){
        //日志
        log.info(":{}团建活动信息查询",name);
        //返回一个分页对象
        PageBean pageBean = adminService.geEmpTeamBuildingActivitiesMsg(id,page,pageSize,name,gender,account,activityDuration,begin,end,empActivityStatus);
        //返回前端分页深数据
        return Result.success(pageBean);
    }

    ///员工团建活动报名表的删除操作
    @DeleteMapping("/empTeamBuildingActivities/{accounts}")
    public Result deleteEmpTeamBuildingActivities(@PathVariable List<String> accounts) {
        log.info("团建活动员工报名表的账号:{}",accounts);
        adminService.deleteEmpTeamBuildingActivities(accounts);
        return Result.success();
    }

    ///管理员对培训获得相关信息的获取和查询
    @GetMapping("/trainingActivity")
    public Result getTrainingActivities(@RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "10") Integer pageSize,
                                        String trainingName,Integer activityStatus,
                                        @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                                        @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime) {
        log.info("培训活动信息表获取或查询");

        //返回一个分页对象
        PageBean pageBean = adminService.getTrainingActivities(page,pageSize,trainingName,activityStatus,startTime,endTime);
        //返回前端一个分页对象的数据
        return Result.success(pageBean);
    }

    ///管理员对培训活动的新增
    @PostMapping("/trainingActivity")
    public Result addTrainingActivity(@RequestBody TrainingActivity trainingActivity){
        //传入对象执行添加操作
        adminService.addTrainingActivity(trainingActivity);
        return Result.success();
    }

    ///管理员对培训活动进行删除
    @DeleteMapping("/trainingActivity/{ids}")
    public Result deleteTrainingActivityByIds(@PathVariable List<Integer> ids) {
        log.info("培训活动表要删除的ids:{}",ids);
        adminService.deleteTrainingActivityByIds(ids);
        return Result.success();
    }

    ///管理员对培训修改时要根据id获取培训活动信息
    @GetMapping("/trainingActivity/{id}")
    public Result getTrainingActivityMsg(@PathVariable Integer id) {
        log.info("修改培训活动的id:{}",id);
        //返回一个培训活动对象
        TrainingActivity trainingActivity = adminService.getTrainingActivityMsgById(id);
        //返回前端一个活动对象
        return Result.success(trainingActivity);
    }

    ///管理员修改培训活动信息
    @PutMapping("/trainingActivity")
    public Result modifyTrainingActivity(@RequestBody TrainingActivity trainingActivity){
        log.info("修改培训活动后的信息:{}",trainingActivity);
        adminService.modifyTrainingActivity(trainingActivity);
        return Result.success();
    }

    ///管理员点击查看某个培训活动的报名信息
    @GetMapping("/empTrainingActivity")
    public Result getEmpTrainingActivity(@RequestParam(defaultValue = "1") Integer page,
                                         @RequestParam(defaultValue = "10") Integer pageSize,
                                         String name,Integer gender,String account,Integer id,
                                         @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                                         @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
                                         Integer activityStatus,String activityDuration,Integer activityScore) {
        log.info("正在查看id为:{}的员工培训活动报名表",id);
        //返回一个pageBean对象
        PageBean pageBean = adminService.getEmpTrainingActivity(page,pageSize,id,name,gender,account,startTime,endTime,activityStatus,activityDuration,activityScore);
        return Result.success(pageBean);
    }

    ///管理员根据员工账号删除员工培训报名表员工的信息
    @DeleteMapping("/empTrainingActivity/{accounts}")
    public Result deleteEmpTrainingActivity(@PathVariable List<String> accounts) {
        log.info("删除的账号:{}",accounts);
        adminService.deleteEmpTrainingActivityByAccounts(accounts);
        return Result.success();
    }

    ///管理员打分操作前会根据账号获取员工的分数
    @GetMapping("/empTrainingActivity/{account}/{id}")
    public Result getEmpTrainingActivityScoreByAccount(@PathVariable String account,@PathVariable Integer id) {
        log.info("获取分数的员工账号:{}",account);
        //返回一个分数
        Integer activityScore = adminService.getEmpTrainingActivityScoreByAccount(account,id);
        //返回前端一个分数
        return Result.success(activityScore);
    }

    ///管理员对于参加培训活动的员工进行打分操作
    @PutMapping("/empTrainingActivity/{account}")
    public Result modifyEmpTrainingActivityScore(@RequestBody String scoreMsg, @PathVariable String account) {
        log.info("管理员进行打分的员工账号:{}",account);
        log.info("管理员打分信息:{}",scoreMsg);
        adminService.modifyEmpTrainingActivityScore(scoreMsg,account);
        return Result.success();
    }

    ///高级管理员对管理员日志的操作
    @GetMapping("/adminOperationLogs")
    public Result getAdminOperationLogs(@RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "10") Integer pageSize,
                                        String username,@RequestParam(defaultValue = "3") Integer rights,
                                        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                                        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime ) {
        log.info("管理员日志获取");
        PageBean pageBean = adminOperationLogService.getAdminOperationLogs(page,pageSize,username,rights,startTime,endTime);
        return Result.success(pageBean);
    }

    ///高级管理员对日志的删除操作
    @DeleteMapping("/adminOperationLogs/{ids}")
    public Result deleteAdminOperationLogs(@PathVariable List<Integer> ids) {
        log.info("删除管理员日志的id:{}",ids);
        //删除管理员日志根据id
        adminOperationLogService.deleteAdminOperationLogs(ids);
        return Result.success();
    }

    ///管理员对员工工资的结算操作
    @PutMapping("/emp/salary")
    public Result addEmpSalary(@RequestBody String empSalary) {
        log.info("员工工资结算信息:{}",empSalary);
        adminService.addEmpSalary(empSalary);
        return Result.success();
    }

    ///管理员批量结算员工工资
    @GetMapping("/emps/salary/{ids}")
    public Result addEmpSalaryByIds (@PathVariable List<Integer> ids,@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate salaryDate) {
        log.info("批量结算员工工资的员工ids:{}",ids);
        adminService.addEmpSalaryByIds(ids,salaryDate);
        return Result.success();
    }

    ///管理员对员工在线信息记录的搜索和获取
    @GetMapping("/empOnline")
    public Result getEmpOnlineMsg(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  String name,String account,
                                  @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                                  @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime) {
        log.info("员工在线信息获取");
        PageBean pageBean = adminService.getEmpOnlineMsg(page,pageSize,name,account,startTime,endTime);
        return Result.success(pageBean);
    }

    ///管理员根据id删除员工在线信息表的信息
    @DeleteMapping("/empOnline/{ids}")
    public Result deleteEmpOnlineMsgByIds(@PathVariable List<Integer> ids) {
        log.info("删除的ID是:{}",ids);
        adminService.deleteEmpOnlineMsgByIds(ids);
        return Result.success();
    }

    ///管理员对员工操作日志的获取和查询
    @GetMapping("/empLog")
    public Result getEmpOperationLogsMsg(@RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "10") Integer pageSize,
                                        String name,String account,String operationType,
                                        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                                        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        log.info("员工日志信息获取");
        PageBean pageBean = empOperationLogService.getEmpOperationLogMsg(page,pageSize,account,name,operationType,startTime,endTime);
        return Result.success(pageBean);
    }

    ///管理员对员工操作日志的删除
    @DeleteMapping("/empLog/{ids}")
    public Result deleteEmpOperationLogsMsg(@PathVariable List<Integer> ids) {
        log.info("删除员工日志的id是:{}",ids);
        empOperationLogService.deleteEmpOperationLogsMsg(ids);
        return Result.success();
    }
}
